package web.weibo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import web.weibo.controller.ControllerHelper;
import web.weibo.mapper.MapperUser;
import web.weibo.model.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.UUID;

@Component
public class ServiceUser {

    private MapperUser mapperUser;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ServiceUser(MapperUser mapperUser) {
        this.mapperUser = mapperUser;
    }

    public static void log(String format, Object... args) {
        System.out.println(String.format(format, args));
    }

    public static String hexFromBytes(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (int i = 0, bytesLength = bytes.length; i < bytesLength; i++) {
            byte currentByte = bytes[i];
            // 02 代表不足两位补足两位 x代表用16进制表示
            // String.format("%02x", 0) = "00"
            result.append(String.format("%02x", currentByte));
        }
        return result.toString();
    }

    public static String SaltedPasswordHash(String password, String salt) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        String salted = salt + password;
        md.update(salted.getBytes(StandardCharsets.UTF_8));
        byte[] result = md.digest();
        return hexFromBytes(result);
    }

    public String login(String username, String password) {
        ArrayList<User> users = this.mapperUser.users();
        for (int i = 0; i < users.size(); i++) {
            User currentUser = users.get(i);
            if (currentUser.username.equals(username)) {
                String salt = currentUser.salt;
                String saltedPassword = ServiceUser.SaltedPasswordHash(password, salt);
                if (currentUser.password.equals(saltedPassword)) {
                    String sessionId = UUID.randomUUID().toString();
                    this.mapperUser.session(sessionId, username);

                    String key = "session";
                    stringRedisTemplate.opsForHash().put(key, sessionId, username);
                    return sessionId;
                }
            }
        }
        return "";
    }

    public static User guest() {
        User user = new User(0, "游客", "8888", "dadasds", UserRole.guest, "dasdas", "null.jpg");
        return user;
    }

    /**
     * 遍历session，拿到当前用户名
     *
     * @param id
     * @return
     */
    public String usernameFromSessionId(String id) {
        ArrayList<Session> sessions = this.mapperUser.sessions(id);
        if (sessions.size() > 0) {
            Session session = sessions.get(0);
            log("session的值为： %s", session);
            return session.username;
        } else {
            return guest().username;
        }

        // log("session改 3");
        // log("session的值是 %s", id);
        //
        // String value = stringRedisTemplate.opsForValue().get("web26");
        // log("value的值是 %s", value);
        //
        // String key = "session";
        // String val = String.valueOf(stringRedisTemplate.opsForHash().get(key, id));
        // return val == null ? guest().username : val;
    }

    /**
     * 得到当前用户信息
     *
     * @param username
     * @return
     */
    public User userFromUsername(String username) {
        ArrayList<User> users = this.mapperUser.users();
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            if (user.username.equals(username)) {
                log("users的值为 %s", user);
                return user;
            }
        }
        return guest();
    }

    /**
     * 判断注册是否成功
     *
     * @param username
     * @param password
     * @return
     */
    public boolean register(String note, String username, String password) {
        String salt = UUID.randomUUID().toString();
        String saltedPassword = ServiceUser.SaltedPasswordHash(password, salt);
        ArrayList<User> users = this.mapperUser.users();
        String avator = "null.jpg";
        int id = users.size() + 1;
        try {
            this.mapperUser.user(id, note, username, saltedPassword, String.valueOf(UserRole.normal), salt, avator);
            log("注册信息： <%s>, <%s>, <%s>, <%s>, <%s>, <%s>, <%s>",
                    id, note, username, saltedPassword, String.valueOf(UserRole.normal), salt, avator);
            return true;
        } catch (Exception e) {
            log("注册异常了 %s", e.getMessage());
            return false;
        }
    }

    /**
     * 修改密码
     *
     * @param username
     * @param newPassword
     * @return
     */
    public String updatePassword(String username, String oldPassword, String newPassword) {
        String message;
        boolean isUser = ControllerHelper.isUser(this.mapperUser, username);
        boolean isPassword = ControllerHelper.isPassword(this.mapperUser, username, oldPassword);
        boolean validPassword = ControllerHelper.formatPass(newPassword);
        if (!isUser) {
            if (isPassword) {
                if (validPassword) {
                    String salt = UUID.randomUUID().toString();
                    String saltedPassword = SaltedPasswordHash(newPassword, salt);
                    this.mapperUser.updatePassword(saltedPassword, salt, username);
                    message = "密码已修改";
                } else {
                    message = "密码格式错误";
                }
            } else {
                message = "旧密码错误";
            }
        } else {
            message = "没有该账号";
        }
        return message;
    }

    public void exit(String username) {
        this.mapperUser.exit(username);
    }
}
